import { sysLogin, sysProfileRequest } from '@/api/user.js'
import { setToken, getToken } from '@/utils/auth'
import router, { constantRoutes } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {},
    routes: []
  },
  mutations: {
    setTokenMutation(state, payload) {
      state.token = payload
      setToken(payload)
    },
    setUserInfoMutation(state, payload) {
      state.userInfo = payload
    },
    setRouters(state, payload) {
      state.routes = [...constantRoutes, ...payload]
    }
  },
  actions: {
    // 这里的两个参数都要写，如果写一个默认为context
    // 高级写法，结构出context里面的commit方法
    async loginAction({ commit }, payload) {
      try {
        const res = await sysLogin(payload)
        commit('setTokenMutation', res.data)
        router.push('/')
        // console.log(data)
      } catch {
        //
      }
    },
    async getUserInfoAction({ commit }, payload) {
      try {
        const res = await sysProfileRequest()
        commit('setUserInfoMutation', res.data)
        // 把用户信息return出去
        return res.data
        // console.log('成功', res)
      } catch {
        console.log('请求失败了')
      }
    },
    logoutAction({ commit }, payload) {
      commit('setTokenMutation', '')
      commit('setUserInfoMutation', {})
    }
  }
}
